﻿using System;
using System.Collections.Generic;

namespace 面向对象_索引器1
{
    class Program
    {
        static void Main(string[] args)
        {
            
            var a = new person("人","耀");
            var b = new person("动物", "狗");
            var d=new person("狗","大狗");
            string c = "动物";
            a.Add(b);
            Console.WriteLine(a);
            Console.WriteLine(a[c]);
            
        }
    }
    // 索引器不必根据整数值类型进行索引，由你决定查找机制
    //  索引器可以被重载
    //  索引器可以有多个形参，如访问二维数组时

    // 通过索引器可以取 List (Array)的值
    class person
    {
        private string nickname;//昵称
        private string name;//名字
        private List<person> people;//人
        public person(string nickname, string name)
        {
            this.name = name;
            this.nickname = nickname;
            people = new List<person>();
        }
        public void Add(person person)
        {

            people.Add(person);
        }
        // key :键值，钥匙 ，字典常用概念
        // 返回值可以自己定义，本例测试了 string、Person 、this
        //public string this[string key]
        //public object this[string key]
        public person this[string nickname]
        {
            get
            {
                // lambda 表达式 
                var pr = people.Find(v => v.nickname == nickname);
                return pr;
            }
            set
            {
                var pr = people.Find(v => v.nickname == nickname);
                if (pr == null)
                {
                    pr.Add(value);
                }
                else
                {
                    pr = value;
                }
            }

        }
        public override string ToString() => name;
    }
}
